﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.IO;
using Wicture.DbRESTFul;
using Wicture.DbRESTFul.Cache;
using Wicture.DbRESTFul.ObjectContainers;
using Wicture.DbRESTFul.Rpc;
using Wicture.DbRESTFul.SQL;
using Wicture.DbRESTFul.Throttle;
using Wicture.Microservice;
using Wicture.QPZS.EPC.Core;
using Wicture.QPZS.EPC.Services;

namespace Wicture.QPZS.EPC
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json");

            if (env.IsDevelopment())
            {
                builder.AddUserSecrets<Startup>();
            }

            Configuration = builder.Build();
        }

        public IConfiguration Configuration { get; }

        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(options => options.Filters.Add(new ApiExceptionFilterAttribute()));
            // services.AddSingleton(services.AddJwtTokenAuthorization());
            RpcRouter.Instance.Register(new EpcRpcRouter());

            services.UseMicroservice(Configuration)
                    .UseCache()
                    .UseSQLStorage();

            var redisConnectionString = ConfigurationManager.Settings.Variables["BlackListStorageService.RedisConnectionString"];
            ThrottleServiceFactory.Init(new RedisBacklistStorageService(redisConnectionString));

            return services.UseAutofacContainer(typeof(Startup).Assembly);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            app.UseCors(builder => builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowCredentials());

            var limitRuleTurnOff = ConfigurationManager.Settings.GetConfigOrDefault<QueryLimitRule>("QueryLimitRule")?.TurnOff == true;
            RouteSetting routeSetting = null;
            if (limitRuleTurnOff)
            {
                LoggerManager.Logger.LogInformation("Disabled api route.");
                routeSetting = new RouteSetting { UseDefaultApiRoutes = false };
            }

            app.UseMicroservice(useRpc: true, routeSetting: routeSetting);

            app.UseMvc();
        }
    }
}
